<script setup lang="ts">
import { computed, onMounted } from "vue";

import useStore from "@src/store/store";

import Chat from "@src/components/views/HomeView/ServiceChat/Chat.vue";
import Navigation from "@src/components/views/HomeView/Navigation/Navigation.vue";
import Sidebar from "@src/components/views/HomeView/Sidebar/Sidebar.vue";
import NoChatSelected from "@src/components/states/empty-states/NoChatSelected.vue";
import Loading3 from "@src/components/states/loading-states/Loading3.vue";
import FadeTransition from "@src/components/ui/transitions/FadeTransition.vue";
import useServiceStore from "@src/store/serviceStore";
import LoginForm from "../AccessView/LoginForm.vue";
import defaults from "@src/store/defaults";
import { getServiceBaseInfo, serviceLogin } from "@src/network/api";
import router from "@src/router";

const store = useStore();

//采用service的setting
store.settings = defaults.serviceSetting

const serviceStore = useServiceStore();

if (!serviceStore.currentService) {
  const un = localStorage.getItem("aivo_un");
  const pd = localStorage.getItem("aivo_pd");
  store.status = "loading"
  if (un && pd) {
    const res = serviceLogin(un,pd).then((res)=>{
      console.log(res)
    if (res.code == '10000') {
      store.status = "success"
      //登录成功记录用户名密码，方便下次获取
      serviceStore.$patch({
        website:res.data.website,
        services:res.data.services,
        customers:res.data.customers,
        conversationRelations:res.data.conversationRelations,
        currentService:res.data.service
      })
      //创建websocket
      setupWebSocket()
    }else{
      router.push('/login')
    }
  });
  } else{
    router.push('/login')
  }
}else{
  if (serviceStore.ws == undefined) {
    console.log('rebuild scoket')
    setupWebSocket()
  }
  store.status = "success"
}

function setupWebSocket(){
  //创建websocket
  console.log('setup socket')
  serviceStore.ws = new WebSocket('wss://www.aivodesk.com/ws?website_id='+serviceStore.website?.id + "&service_id=" + serviceStore.currentService?.id)
  serviceStore.ws.onmessage = (event) => {
      //收到自己发出去的信息
      const res =  JSON.parse(event.data);
      console.log(res.data)
        if(res.type == 'receive') {
          const conversation = res.data;
          serviceStore.addConversation(conversation);
        } else if (res.type == 'ai') {
          const conversation = res.data;
          serviceStore.addAiMessage(res.msg,res.data.relation_id)
          // serviceStore.addConversation(conversation);
        } else if (res.type == 'normal') {
          const conversation =  res.data;
          serviceStore.addConversation(conversation);
        } else if (res.type == 'buildRelation') {
          if (res.data.id in serviceStore.conversationRelations) {
            serviceStore.conversationRelations[res.data.id].customer_status = 'on'
          }else{
            serviceStore.conversationRelations[res.data.id] = res.data;
          }
          
        } else if (res.type == 'offline') {
          const customer_id : number = res.data.customer_id;
          serviceStore.customerOffLine(customer_id);
        }
    };


    serviceStore.ws.onclose = () => {
      if (serviceStore.currentService) {
        serviceStore.ws = new WebSocket('wss://www.aivodesk.com/ws?website_id='+serviceStore.website?.id + "&service_id=" + serviceStore.currentService?.id)  
      }
    };

    serviceStore.ws.onerror = (error) => {
      if (serviceStore.currentService){
        serviceStore.ws = new WebSocket('wss://www.aivodesk.com/ws?website_id='+serviceStore.website?.id + "&service_id=" + serviceStore.currentService?.id)
      }
      //错误也应该重连
      
    };
}

// the active chat component or loading component.
const activeChatComponent = computed((): any => {
  if (serviceStore.currentConversationRelationId) { //当前有选中的用户
    return Chat;
  } else {
    return NoChatSelected;
  }
});

</script>

<template>
  <KeepAlive>
    <div
      class="xs:relative md:static h-full flex xs:flex-col md:flex-row overflow-hidden"
    >
      <!--navigation-bar-->
      <Navigation class="xs:order-1 md:-order-none" />
      <!--sidebar-->
      <Sidebar
        class="xs:grow-1 md:grow-0 xs:overflow-y-scroll md:overflow-visible scrollbar-hidden"
      />
      <!--chat-->
      <div
        id="mainContent"
        class="xs:absolute xs:z-10 md:static grow h-full xs:w-full md:w-fit scrollbar-hidden bg-white dark:bg-gray-800 transition-all duration-500"
        :class="
          store.conversationOpen === 'open'
            ? ['xs:left-[0px]', 'xs:static']
            : ['xs:left-[1000px]']
        "
        role="region"
      >
        <FadeTransition name="fade" mode="out-in">
          <component
            :is="activeChatComponent"
            :key="serviceStore.currentConversationRelationId"
          />
        </FadeTransition>
      </div>
    </div>
  </KeepAlive>
</template>
